<template>
  <div class="login-container">
    <div class="login-form-wrapper">
      <div class="login-header">
        <h2>用户登录</h2>
        <p>欢迎回来，请登录您的账户</p>
      </div>
      
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="loginFormRef"
        class="login-form"
        size="large"
      >
        <el-form-item prop="username">
          <el-input 
            v-model="form.username" 
            placeholder="请输入用户名"
            prefix-icon="User"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input 
            v-model="form.password" 
            placeholder="请输入密码" 
            type="password"
            prefix-icon="Lock"
            show-password
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            class="login-button"
            :loading="loading"
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
        
        <div class="login-footer">
          <span>还没有账户？</span>
          <router-link to="/register" class="register-link">立即注册</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const loginFormRef = ref<FormInstance>()

const loading = ref(false)

const form = reactive({
  username: '',
  password: ''
})

const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少 6 个字符', trigger: 'blur' }
  ]
})

const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) return

    loading.value = true
    
    console.log('开始处理登录...')
    
    // 调用登录方法
    const result = await userStore.login(form.username, form.password)
    
    console.log('登录结果:', result)
    console.log('当前用户状态:', userStore.currentUser)
    console.log('登录状态:', userStore.isLoggedIn)
    console.log('管理员状态:', userStore.isAdmin)
    console.log('用户角色:', userStore.userRole)
    
    if (result.success) {
      ElMessage.success('登录成功！')
      
      // 等待状态更新完成
      await nextTick()
      
      console.log('跳转前状态检查:', {
        isLoggedIn: userStore.isLoggedIn,
        isAdmin: userStore.isAdmin,
        userRole: userStore.userRole
      })
      
      // 检查 localStorage 状态
      console.log('localStorage 状态:', {
        token: localStorage.getItem('token'),
        isLoggedIn: localStorage.getItem('isLoggedIn'),
        userRole: localStorage.getItem('userRole')
      })
      
      // 根据用户角色跳转
      if (userStore.isAdmin) {
        console.log('跳转到管理员页面')
        router.push('/admin/users')
      } else {
        console.log('跳转到用户仪表板')
        router.push('/dashboard')
      }
    } else {
      ElMessage.error(result.message || '登录失败')
    }
    
  } catch (error: any) {
    console.error('登录过程错误:', error)
    
    if (error?.errors) {
      // 表单验证错误
      return
    }
    
    ElMessage.error('登录失败，请检查用户名和密码')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 样式保持不变 */
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-form-wrapper {
  background: white;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  width: 100%;
  max-width: 400px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #2c3e50;
  margin-bottom: 8px;
  font-size: 28px;
  font-weight: 600;
}

.login-header p {
  color: #7f8c8d;
  margin: 0;
  font-size: 14px;
}

.login-form {
  width: 100%;
}

.login-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  margin-top: 10px;
}

.login-footer {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ecf0f1;
  color: #7f8c8d;
  font-size: 14px;
}

.register-link {
  color: #3498db;
  text-decoration: none;
  margin-left: 8px;
  font-weight: 500;
}

.register-link:hover {
  color: #2980b9;
  text-decoration: underline;
}

@media (max-width: 480px) {
  .login-form-wrapper {
    padding: 30px 20px;
  }
  
  .login-header h2 {
    font-size: 24px;
  }
}
</style>